﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using System.IO;
using System.Diagnostics;
using System.Xml.Linq;
using BYRBBS.Model;
using BYRBBS.Util;

namespace BYRForum
{
    public partial class ReplyPopup : UserControl
    {
        string appendText = "";
        string replyTitle;
        string replyContent;
        ThreadsDetailPage basePage;
        public ReplyPopup(PhoneApplicationPage parent)
        {
            InitializeComponent();
            basePage = (ThreadsDetailPage)parent;
            TextReplyTitle.Text ="RE:"+ App.ArticleList.Items[0].Article_Item.Title;
            appendText = "【在" + App.ArticleList.Items[App.ArticleItemChoose].Article_Item.author.Id + "的大作中提到: 】\n";
            string[] originText = App.ArticleList.Items[App.ArticleItemChoose].Article_Item.Content.Split('\n');
            
            for (int i = 0; i < originText.Length; i++)
            {
                appendText += ": " + originText[i] + "\n";
                if (i > 1) break;
            }
            appendText += ": ...................\n";
            Debug.WriteLine("appendText:" + appendText);
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (TextReplyTitle.Text == "" || TextReplyContent.Text == "")
            {
                MessageBox.Show("回复内容或标题不能为空！");
                return;
            }
            replyContent = TextReplyContent.Text;
            replyTitle = TextReplyTitle.Text;
            string url = ByrApi.apiUrl + "/article/" + App.ArticleList.Items[App.ArticleItemChoose].Article_Item.Board_name + "/post" + ByrApi.Encode + ByrApi.appkey;
            HttpUtil.HttpPost(url, PostAriticle_Callback);
            progressBarWait.Visibility = Visibility.Visible;

            
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.CloseMeAsPopup();
        }

        private void PostAriticle_Callback(IAsyncResult asynchronousResult)
        {

            try
            {
                HttpWebRequest hwrq = (HttpWebRequest)asynchronousResult.AsyncState;
                string content = "";
                Stream responseStream = hwrq.EndGetRequestStream(asynchronousResult);
                StreamWriter sr = new StreamWriter(responseStream);
                if (App.ArticleItemChoose == 0)
                {

                    content = replyContent + "\n来自：Windows Phone 7 客户端-alpha";
                }
                else
                {
                    content = replyContent + "\n" + appendText + "\n\n\n来自：Windows Phone 7 客户端-alpha";
                }

                sr.Write("title=" + replyTitle + "&content=" + content + 
                    "&reid=" + App.ArticleList.Items[App.ArticleItemChoose].Article_Item.Reply_id + "&signature=1");
                sr.Close();
                responseStream.Close();
                hwrq.BeginGetResponse(PostResponse_Callback, hwrq);
            }
            catch (Exception e)
            {
                Debug.WriteLine("POST STRING FAILED:" + e.Message);
            }
        }
        private void PostResponse_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                XDocument doc = XDocument.Parse(result);
                Debug.WriteLine(result);
                foreach (XElement item in doc.Descendants("error").Nodes())
                {
                    if (item.Name == "msg")
                    {
                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                MessageBox.Show("回复失败：" + item.Value);
                                progressBarWait.Visibility = Visibility.Collapsed;

                            }
                            );


                        return;
                    }
                }
                this.Dispatcher.BeginInvoke(
                    () =>
                    {
                        MessageBox.Show("回复成功！");
                        progressBarWait.Visibility = Visibility.Visible;
                        basePage.GoToPage(basePage.current_page);
                        this.CloseMeAsPopup();
                    }
                    );



            }
            catch { }

            

        }
    }
}